package com.atguigu.gmallpublisher1.controller;

import com.atguigu.gmallpublisher1.service.ProductStatsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

//@Controller
@RestController
@RequestMapping("api/sugar/")
public class SugarController {

    @Autowired
    private ProductStatsService productStatsService;

    @RequestMapping("test")
    //@ResponseBody
    public String test1() {
        System.out.println("111111111");
        return "success";
    }

    @RequestMapping("test2")
    public String test2(@RequestParam("name") String nn,
                        @RequestParam(value = "age", defaultValue = "18") int age) {
        System.out.println("Name:" + nn + ",Age:" + age);
        return "success";
    }

    @RequestMapping("gmv")
    public String getGmv(@RequestParam(value = "date", defaultValue = "0") int date) {

        //处理时间,如果外部没有传入时间参数,则自动改为当天
        if (date == 0) {
            date = getToday();
        }

        //查询ClickHouse数据
        BigDecimal gmv = productStatsService.getGmv(date);

        //返回结果
        return "{" +
                "  \"status\": 0," +
                "  \"msg\": \"\"," +
                "  \"data\": " + gmv +
                "}";
    }


    @RequestMapping("trademark")
    public String getGmvByTrademark(@RequestParam(value = "date", defaultValue = "0") int date,
                                    @RequestParam(value = "limit", defaultValue = "5") int limit) {

        //处理时间,如果外部没有传入时间参数,则自动改为当天
        if (date == 0) {
            date = getToday();
        }

        //查询ClickHouse数据
        Map gmvByTrademark = productStatsService.getGmvByTrademark(date, limit);
        Set tmNames = gmvByTrademark.keySet();
        Collection gmvs = gmvByTrademark.values();

        //封装JSON数据并返回
        return "{" +
                "  \"status\": 0," +
                "  \"msg\": \"\"," +
                "  \"data\": {" +
                "    \"categories\": [\"" +
                StringUtils.join(tmNames, "\",\"") +
                "\"]," +
                "    \"series\": [" +
                "      {" +
                "        \"name\": \"GMV:\"," +
                "        \"data\": [" +
                StringUtils.join(gmvs, ",") +
                "]" +
                "      }" +
                "    ]" +
                "  }" +
                "}";
    }

    private int getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String todayStr = sdf.format(System.currentTimeMillis());
        return Integer.parseInt(todayStr);
    }

}
